<template>
    <a-drawer
      :title="title"
      :maskClosable="true"
      :width="drawerWidth"
      placement="right"
      :closable="true"
      @close="handleCancel"
      :visible="visible"
      style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
      <a-form :form="form">
    <a-spin :spinning="confirmLoading">
      <a-button @click="setLightAddress" style="margin-right:10px" type="primary" icon="plus"> {{$t('light.writeAddress')}} </a-button>
      <a-button @click="getLightAddress" style="margin-right:10px" type="primary" icon="plus"> {{$t('light.readAddress')}} </a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="headers" :action="importLightAddress"
                @change="handleImportExcelLightAddress">
        <a-button type="primary" icon="import"> {{$t('light.importAddress')}} </a-button>
      </a-upload>
      <div style="margin-bottom:10px"></div>
      <div>
        <a-row  style="margin-bottom:10px" :gutter="16" v-for="(item, index) in addressList" :key="index">
          <a-col :span="1" style="width: 36px;padding-right:inherit;padding-left:8px;text-align: right;line-height: 30px;">
              {{index+1}}.
          </a-col>
          <a-col :span="5">
            <a-input maxlength="4" v-model="addressList[index]" />
          </a-col>
        </a-row>
      </div>
    </a-spin>
      </a-form>
    </a-drawer>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import {duplicateCheck } from '@/api/api'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import Vue from 'vue'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  export default {
    name: "GlrLightGateWayAddress",
    components: {
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title:this.$t('light.subControlAddress') ,
        width:800,
        visible: false,
        drawerWidth:700,
        model: {},
        addressList:[],
        addressListbak:"",
        headers: {},
        gateWayCode:'',
        disableMixinCreated:true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        url: {
          add: "/glr/glrGateway/add",
          edit: "/glr/glrGateway/edit",
          readLightAddress:"/glr/glrGateway/readLightAddress",
          setLightAddress:"/glr/glrGateway/setLightAddress",
          importLightAddress: window._CONFIG['domianURL']+"/glr/glrGateway/importLightAddress?gateWayCode=",
        }
      }
    },
    computed: {
      importLightAddress: function () {
        return this.url.importLightAddress+this.gateWayCode;
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token};
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        const that = this;
        that.confirmLoading = true;
        this.visible = true;
        this.gateWayCode=record.gateWayCode;
        let httpurl =this.url.readLightAddress;
        httpAction(httpurl,{gateWayCode:record.gateWayCode},"post").then((res)=>{
          if(res.success){
            that.addressList=res.result.data;
            console.info(that.addressList);
            //that.$message.success(res.message);
            that.$message.success(that.$t('base.operationSuccessful'));
            that.$emit('ok');
          }else{
            //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
          }
        }).finally(() => {
          that.confirmLoading = false;
        })


      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl =this.url.readLightAddress;
            httpAction(httpurl,formData,"post").then((res)=>{
              if(res.success){
                //that.$message.success(res.message);
                that.$message.success(that.$t('base.operationSuccessful'));
                that.$emit('ok');
              }else{
                //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }

        })
      },
      fanzhuan(array){
        var temp = [];
        for(var i=array.length-1;i>=0;i--){
          temp[temp.length]=array[i];
        }
        for(var j=0;j<temp.length;j++){
          array[j]=temp[j];
        }
        return array;
      },
      isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == ""){
          return true;
        }else{
          return false;
        }
      },
      setLightAddress(){

        this.addressListbak="";
        this.addressListbak = this.addressList.join(',');

        var  arr=this.addressList;
        arr=this.fanzhuan(arr);

        var temp = [];
        var bFirst=false; //找到第一个非空的标志
        for(var j=0;j<arr.length;j++){
          if (!this.isEmpty(arr[j])) {
            temp[temp.length]=arr[j];
            bFirst=true;
          }else{
            if (bFirst){
              temp[temp.length]=arr[j];
            }
          }
        }
        temp=this.fanzhuan(temp);

        var address=temp.join(",");
        const that = this;

        var arr1 = this.addressListbak.split(',');
        this.addressList=arr1;

        this.$confirm({
          title: this.$t('base.confirm'),
          content: this.$t('light.confirmWriteAddress') ,
          onOk: function () {
            that.loading = true;
            that.confirmLoading = true;
            let httpurl =that.url.setLightAddress;
            httpAction(httpurl,{gateWayCode:that.gateWayCode,address:address},"post").then((res)=>{
              if(res.success){
                //that.$message.success(res.message);
                that.$message.success(that.$t('base.operationSuccessful'));
                //that.$emit('ok');
              }else{
                //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      getLightAddress(){
        const that = this;
        that.confirmLoading = true;
        this.visible = true;
        let httpurl =this.url.readLightAddress;
        httpAction(httpurl,{gateWayCode:this.gateWayCode},"post").then((res)=>{
          if(res.success){
            that.addressList=res.result.data;
            console.info(that.addressList);
            //that.$message.success(res.message);
            that.$message.success(that.$t('base.operationSuccessful'));
            that.$emit('ok');
          }else{
            //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
          }
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'currentWorkStatus','phoneNumber','phoneType','gatewayModel','gatewayType','longitude','latitude','gatewayName','gateWayCode','sysCompanyCode','controlNumber','controlModel','currentPeriod','dimmingValue','switchingState','temperature','humidity','voltageA','voltageB','voltageC','currentA','currentB','currentC','illuminance','outage','signalValue','cellVoltage'))
      },
      /* 导入 */
      handleImportExcelLightAddress(info){
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let { message, result: { msg, fileUrl, fileName } } = info.file.response
              let href = window._CONFIG['domianURL'] + fileUrl
              this.$message.error(`操作失败: ${info.file.msg} `);
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} 操作成功`)
            }
            this.loadData()
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`操作失败: ${info.file.msg} `);
        }
      },

    }
  }
</script>

<style scoped>

</style>